var express = require("express");
var router = express.Router();
var { dispositionModel, studentModel, paperModel, questionModel, resultModel } = require("../model/model");
//登录
router.post('/examlogin', async (req, res) => {
   let { name, card, tid } = req.body
   let result = await studentModel.find({ $and: [{ name }, { card }, { tid }] })
   if (result.length > 0) {
      res.send({
         code: 200,
         sid: result[0]._id,
         clazz: result[0].clazz,
         sname: result[0].name
      })
   } else {
      res.send({
         code: 400,
         sid: ''
      })
   }
})
//获取学生信息
router.get("/getstudent", async (req, res) => {
   let { _id } = req.query
   let data = await studentModel.findOne({ _id }).populate('clazz')
   res.send({
      code: 200,
      data
   })
});
//获取试卷信息
router.get("/getpaper", async (req, res) => {
   let { clazzid } = req.query
   let data = await paperModel.find({ class: clazzid, flag: 2 });

   res.send({
      code: 200,
      data
   })
});

router.get('/getresult2',async(req,res)=>{
   let {_id} = req.query;
   console.log(_id);
   
   let data = await resultModel.findOne({status:true,paper:_id})
   if (data?.grade) {
      res.send({code:200,grade:data.grade})
   }else{
      res.send({
         code:500
      })
   }
})
//获取试题信息
router.get("/getshiti", async (req, res) => {

   let { sid, paperid } = req.query;
   let paper = await paperModel.findOne({ _id: paperid });
   let questionsArr = [];

   if (paper.type) {
      let data = paper.questions;
      // 使用 Promise.all 来并行获取所有问题
      questionsArr = await Promise.all(
         data.map(async (v) => {
            return await questionModel.findOne({ _id: v });
         })
      );
   }
   else {
      let obj = await dispositionModel.findOne({ pid: paperid }).select('radio checkbox short judgment')
      let aa = await getRandomElementsFromData(obj)
      let arr1 = aa.radio.map(async item => {
         let obj = await questionModel.findOne({ _id: item })
         return obj
      })
      let arr2 = aa.checkbox.map(async item => {
         let obj = await questionModel.findOne({ _id: item })
         return obj
      })
      let arr3 = aa.judgment.map(async item => {
         let obj = await questionModel.findOne({ _id: item })
         return obj
      })
      let arr4 = aa.short.map(async item => {

         let obj = await questionModel.findOne({ _id: item })
         return obj
      })
      questionsArr = await Promise.all([...arr1, ...arr2, ...arr3, ...arr4]);

   }
   res.send({
      code: 200,
      data: questionsArr,
   });

})
// Fisher-Yates 洗牌算法用于随机抽取元素
function getRandomElements(arr, n) {
   const shuffled = arr.slice();
   for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
   }
   return shuffled.slice(0, n);
}

// 过滤并随机抽取题目
async function getQuestionsByType(arr, count, cateValue) {
   const questions = await questionModel.find({
      belong: { $in: arr }, // 从题库中查找属于 arr 中任一 stage 的问题
      cate: cateValue, // 过滤出指定类型的题目
   });

   return getRandomElements(
      questions.map((q) => q._id),
      count
   );
}

// 主函数
async function getRandomElementsFromData(data) {
   let newobj = {
      radio: data.radio,
      checkbox: data.checkbox,
      judgment: data.judgment,
      short: data.short
   }
   const result = {};
   for (const key in newobj) {
      if (newobj.hasOwnProperty(key)) {
         const { arr, count } = newobj[key];
         let cateValue; // 根据键名确定 cate 值
         switch (key) {
            case "radio":
               cateValue = 1;
               break;
            case "checkbox":
               cateValue = 2;
               break;
            case "judgment":
               cateValue = 3;
               break;
            case "short":
               cateValue = 4;
               break;
            default:
               continue;
         }
         result[key] = await getQuestionsByType(arr, count, cateValue);
      }
   }
   return result;
}

//人脸部分
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
const IaiClient = tencentcloud.iai.v20200303.Client;
const clientConfig = {
   credential: {
      secretId: "AKIDd8PUQ9ev495GPOAmBSbaP1SgjYCmcJsJ",
      secretKey: "OccQAoHZgeQzLYdmjTUj1ISTIwNbdait",
   },
   region: "ap-beijing",
   profile: {
      httpProfile: {
         endpoint: "iai.tencentcloudapi.com",
      },
   },
};
// 实例化客户端
const client = new IaiClient(clientConfig);

// 创建一个路由来处理人脸识别请求
router.post("/verify-face", async (req, res) => {
   const params = {
      Image: req.body.image,
      PersonId: req.body.personId,
   };

   client.VerifyFace(params)
      .then((data) => {
         res.json(data);
      })
      .catch((err) => {
         console.error("Error:", err);
         res.status(500).json({ error: err.message });
      });
});

//添加考生答案
router.post("/addRequest", async (req, res) => {
   // console.log(req.body);

   let { result, sid, paperid, clazz, startTime } = req.body;
   let newresult;
   // 使用 Object.keys() 检查 result 是否为空对象
   if (Object.keys(result).length === 0) {
      newresult = { 'result': null }; // 或者可以设置为默认值
   } else {
      newresult = result;
   }
   let endTime = Date.now();
   let time = [Number(startTime), endTime];
   console.log(time);

   await resultModel.create({ result: newresult, student: sid, paper: paperid, time: time, clazz: clazz });

   res.send({
      code: 200,
   });
});

//获取考生分数
// router.get('/getresult2',async(req,res)=>{
//    let {_id} = req.query
//    console.log(req.query);
   
//    let data = await resultModel.find({student:_id})
//    // console.log(data.map(item=>{return {p:item.paper,g:item.grade}}));
   
//    res.send({
//       code:200,
//       // data:data.grade
//    })
// })
module.exports = router;